package org.bpms.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.bpms.model.admin.Suser;
import org.bpms.plugins.bjui.BjuiRender;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.JFinal;

/**
 * 全局拦截器
 * @author hupei
 *
 */
public class GlobalInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation ai) {
		Suser user = ai.getController().getSessionAttr("user");
		if (null == user){
			if (ai.getActionKey().equals("/admin/info")){//刷新页面
				ai.getController().redirect("/admin");
			}else if(ai.getActionKey().equals("/wechat")){
				ai.invoke();
			}else{//点击菜单时
				ai.getController().render(BjuiRender.timeout());
			}
		}else{
			if(!JFinal.me().getConstants().getDevMode()){
				//异常集中返回json
				try {
					ai.invoke();
				} catch (RuntimeException e) {
					//最多处理10次嵌套查询原始出错信息
					Throwable t = e.getCause();
					for (int i = 0; i < 10; i++) {
						if(StringUtils.isNotBlank(t.getMessage())){
							ai.getController().render(BjuiRender.error(t.getMessage()));
							return;
						}
						t = t.getCause();
					}
					throw new RuntimeException(e);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}else{
				ai.invoke();
			}			
		}		
	}

}
